/* 
 * Copyright [2018] [Alex/libo(liboms@hotmail.com)]
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *  http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.hyts.shell.executor;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Objects;
import java.util.Properties;
import java.util.logging.Logger;

import org.apache.commons.io.IOUtils;

import com.hyts.shell.cache.ICache;
import com.hyts.shell.cache.ICacheFactory;
import com.hyts.shell.config.SSHConfig;
import com.hyts.shell.error.SSHException;
import com.hyts.shell.executor.base.Executor;
import com.hyts.shell.handler.AbstractStreamHandler;
import com.hyts.shell.handler.BaseProcessStream;
import com.hyts.shell.model.ExecuteDomain;
import com.hyts.shell.model.ResultDomain;
import com.hyts.shell.model.StringResultDomain;
import com.hyts.shell.model.UserRealm;
import com.jcraft.jsch.Channel;
import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;

import ch.ethz.ssh2.Connection;


/** 
 * @title JcachExecutor.java  
 * @package com.hyts.shell.executor  
 * @description TODO  
 * @see TODO
 * @author libo/Alex
 * @email liboms@hotmail.com/liboware@163.com  
 * @date 2018年5月25日 
 * @version V1.0 
 */
public class JcraftExecutor  implements Executor<ExecuteDomain,ResultDomain>{

	/**  
	 * <p>流处理器-抽象类</p> 
	 * @fieldName handler
	 * @fieldType AbstractStreamHandler
	 */ 
	AbstractStreamHandler handler = null;
	
	/**  
	 * <p>基础接口缓存操作</p> 
	 * @fieldName cache
	 * @fieldType ICache
	 */ 
	ICache cache = null;
	
	
	private int timeout = 60000;
	
	/**
	 * <p>
	 * 构建连接线程隔离操作
	 * </p>
	 * @fieldName connections
	 * @fieldType ThreadLocal<Connection>
	 */
	private static ThreadLocal<Session> connections = new ThreadLocal<Session>();
	
	/**  
	 * <p>jsch:基础SSH登录</p> 
	 * @fieldName jsch
	 * @fieldType JSch
	 */ 
	JSch jsch = new JSch();
	/**
	 * <p>
	 *  日志输出器
	 * </p>
	 * @fieldName logger
	 * @fieldType Logger
	 */
	Logger logger = Logger.getLogger(EthzExecutor.class.getName());

	/**  
	 * @constructor：EthzExecutor  
	 * @param handler
	 * @param cache  
	 */ 
	public JcraftExecutor(AbstractStreamHandler handler, ICache cache) {
		super();
		this.handler = handler;
		this.cache = cache;
	}

	/**  
	 * @constructor：SSH2Excecutor  
	 * @param handler  
	 */ 
	public JcraftExecutor(AbstractStreamHandler handler) {
		super();
		this.handler = handler;
		cache = new ICacheFactory().getSessionCacheManager();
	}
	
	/**  
	 * @constructor：SSH2Excecutor    
	 */ 
	public JcraftExecutor() {
		super();
		this.handler = new BaseProcessStream();
		cache = new ICacheFactory().getSessionCacheManager();
	}
	
	@Override
	public boolean login(UserRealm userDomain) throws SSHException {
		if (userDomain != null)
			new SSHException("不允许传入空得用户认证信息!");
		try {
			if (null == connections.get()) {
				build(userDomain);
			}
		} catch (JSchException e) {
			throw new SSHException(e);
		}
		return true;
	}

	/**
	 * @throws IOException <b>build</b> <p>构建方法操作：构建Connection对象连接</p> @param
	 * conn @param domain @exception
	 * @throws JSchException 
	 */
	private void build(UserRealm domain) throws JSchException {
		Session connectSession = jsch.getSession(domain.getUserName(), domain.getIp(), domain.getPort() == null ? SSHConfig.DEFAULT_SSH_PORT : domain.getPort());
		connectSession.setPassword(domain.getPassword());
		Properties config = new Properties();
		config.put("StrictHostKeyChecking", "no");
		connectSession.setConfig(config); // 为Session对象设置properties
		connectSession.setTimeout(timeout); // 设置timeout时间
		connectSession.connect();
		connections.set(connectSession);
	}

	/**
	 * <b>getConnection</b> 
	 * <p>获取连接包含自动登录操作</p> 
	 * @param userDomain 
	 * @return @exception
	 */
	public Session getConnection(UserRealm userDomain) {
		if (login(userDomain)) {
			return connections.get();
		}
		return null;
	}

	/*
	 * (非 Javadoc) 
	 * @param conn
	 * @return
	 * @see com.hyts.shell.executor.base.Executor#close(ch.ethz.ssh2.Connection)
	 * @exception
	 */
	@Override
	public boolean close() {
		Session conn = connections.get();
		if (conn != null) {
			connections.set(null);
			connections.remove();
		}
		return false;
	}

	
	/* (非 Javadoc)
	 * @param param
	 * @return
	 * @see com.hyts.shell.executor.base.Executor#execute(java.lang.Object)  
	 * @exception
	 */ 
	@SuppressWarnings("unchecked")
	@Override
	public ResultDomain<String> execute(ExecuteDomain param) {
		Session conn = null;
		ResultDomain<String> result = new StringResultDomain();
    	if(cache.getValue(param) == null) {
    		conn = getConnection(param);
    		cache.putValue(param, conn);
    	}else {
    		System.out.println("读取缓存");
    		conn = (Session) cache.getValue(param);
    	}
		Channel channel = null;
		BufferedReader input = null;
		ChannelExec channelExec = null;
		try {
			channel = conn.openChannel("exec");
			channelExec = (ChannelExec) channel;
			channelExec.setCommand(param.execCommand);
			channelExec.setInputStream(null);
			result.setResultSubject((String) handler.processStream(channelExec.getInputStream(), "UTF-8"));
			channelExec.connect();
			System.out.println("The remote command is :" + param.execCommand);
			// 得到returnCode
			if (channelExec.isClosed()) {
				result.setExitStatus(channelExec.getExitStatus());
			}
		} catch (JSchException | IOException e) {
			e.printStackTrace();
		} finally {
			IOUtils.closeQuietly(input);
			// 关闭通道
			channelExec.disconnect();
			// 关闭session
			conn.disconnect();
		}
		return result;
	}
	
}
